import http from '../utils/http'
import constant from '../utils/constant'
import store from '../vuex/mobile'
import {delCookie} from '../utils/utils'

export default {
  name: 'login',
  data() {
    return {
      name: '',
      phase: 'login',
      disabled: true,
      selectedMobile: '',
      verificationCode: '',
      msg: '',
      logined: this.$store.getters.getMobile === null ? false : true,
      codeContent: '点击获取验证码',
      totalTime: 60,
      canClick: true,
      showAgentApply: false,
      showPersonalApply: false,
      token: '',
      districts: [],
      personalForm: {
        districtId: '',
        agentName: '',
        agentMobile: '',
        agentEmail: '',
        companyName: ''
      },
      hasPassword: false,
      userName: '',
      setPassword: false,
      setPasswordVal: '',
      verificationPassword: ''
    }
  },

  created() {
  },

  methods: {

    // 页面切换
    switchForm(event) {
      this.phase = event.target.dataset['phase']
      this.requestDistricts()
      this.$set(this.$data, 'personalForm', {
        districtId: '',
        agentName: '',
        agentMobile: '',
        agentEmail: '',
        companyName: ''
      })
    },

    //密码\验证码登录切换
    toggleLogin() {
      this.hasPassword = !this.hasPassword
    },

    // 展示消息弹窗
    showMsgModal(msg) {
      let that = this
      this.$set(this.$data, 'msg', msg)
      this.$bvModal.show('msg-modal')
      setTimeout(function () {
        that.$bvModal.hide('msg-modal')
      }, 3000)
    },

    // 手机校验
    isMobile(mobile) {
      return mobile && (/^((13)|(15)|(17)|(18)|(19))\d{9}$/.test(mobile) || /^[+]852\d{8}$/.test(mobile) || /^[+]853\d{8}$/.test(mobile))
    },

    // 邮箱校验
    isEmial(email) {
      return email && /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(email)
    },
    // 密码校验
    isPassword: function(password) {
      // eslint-disable-next-line no-tabs
    	return password &&  /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,20}$/.test(password)
    },

    // 用户登录
    userLogin() {
      const that = this

      if(that.hasPassword) {
        that.togglePasswordLogin();
        
      } else {

        if (this.selectedMobile === '') {
          that.$root.$emit('bv::show::tooltip', 'userMobile')   // 手机号不存在
          setTimeout(function () {
            that.$root.$emit('bv::hide::tooltip')
          }, 1500)
        } else if (this.verificationCode === '') {
          that.$root.$emit('bv::show::tooltip', 'code')  //验证码不存在
          setTimeout(function () {
            that.$root.$emit('bv::hide::tooltip')
          }, 1500)
        } else {      //执行提交
          http.post(constant.login, {
            'mobile': that.selectedMobile,
            'code': that.verificationCode,
            'token': that.token
          }, function (response) {
            console.log(response)
            that.showMsgModal('登录成功！')
            store.dispatch('setMobile', response.agent.mobile)
            store.dispatch('setUserName', response.agent.name)

            window.clearInterval(that.clock)

            if(!response.agent.has_password) {
              that.setPassword = true
              that.mobile = response.agent.mobile
            } else {
              that.setPassword = false
              setTimeout(function () {
                let redirect = decodeURIComponent(that.$route.query.redirect || '/');
                that.$router.push({
                  path: redirect
                })
              }, 1500)
            }
            //this.$store.dispatch('setUserInfo', user);
          }, function (response) {
            that.showMsgModal(response.message)
          })
        }
      }
    },

    togglePasswordLogin() {
      let that = this
      if (this.userName === '' || (!this.isMobile(this.userName) && !this.isEmial(this.userName))) {
        that.$root.$emit('bv::show::tooltip', 'userName')   // 用户名不存在
        setTimeout(function () {
          that.$root.$emit('bv::hide::tooltip')
        }, 1500)
      } else if (this.verificationPassword === '' || !this.isPassword(this.verificationPassword)) {
        that.$root.$emit('bv::show::tooltip', 'password')  //密码不对
        setTimeout(function () {
          that.$root.$emit('bv::hide::tooltip')
        }, 1500)
      } else {      //执行提交
        http.post(constant.login, {
          'mobile': that.userName,
          'password': that.verificationPassword
        }, function (response) {
          console.log('mima',response)
          that.showMsgModal('登录成功！')
          store.dispatch('setMobile', response.agent.mobile)
          store.dispatch('setUserName', response.agent.name)

          setTimeout(function () {
            let redirect = decodeURIComponent(that.$route.query.redirect || '/');
            that.$router.push({
              path: redirect
            })
          }, 1500)
          //this.$store.dispatch('setUserInfo', user);
        }, function (response) {
          that.showMsgModal(response.message)
        })
      }
    },

    // 密码设置
    bindSetPassword() {
      const that = this
      
      if (this.setPasswordVal === '' || !this.isPassword(this.setPasswordVal) ) {
        that.$root.$emit('bv::show::tooltip', 'repeat-password')   //密码
        setTimeout(function () {
          that.$root.$emit('bv::hide::tooltip')
        }, 1500)
      } else if(this.verificationPassword === '' || !this.isPassword(this.verificationPassword)) {
        that.$root.$emit('bv::show::tooltip', 'different-password')   //密码
        setTimeout(function () {
          that.$root.$emit('bv::hide::tooltip')
        }, 1500)
      } else if (this.setPasswordVal != this.verificationPassword) {
        that.$root.$emit('bv::show::tooltip', 'different-password')  //密码不存在
        setTimeout(function () {
          that.$root.$emit('bv::hide::tooltip')
        }, 1500)
      }  else {      //执行提交
        http.post(constant.setPassword, {
          'mobile': that.mobile,
          'password': that.setPasswordVal,
          '_method': 'PATCH'
        }, function (response) {
          console.log('shezhi', response)
          that.showMsgModal('设置密码登录成功！')
          setTimeout(function () {
            let redirect = decodeURIComponent(that.$route.query.redirect || '/profile');
            that.$router.push({
              path: redirect
            })
          }, 1500)
          //this.$store.dispatch('setUserInfo', user);
        }, function (response) {
          that.showMsgModal(response.message)
        })
      }
    },

    // 用户登出
    logoutFun() {
      delCookie(constant.mobileCookie)
      store.dispatch('setMobile', null)
      store.dispatch('setUserName', null)
      this.$router.go()
    },

    // 获取验证码
    getCode() {
      const that = this

      // 获取验证码
      function requestVerifyCode(mobile, success, failure) {
        http.post(constant.verfityCode, {mobile: mobile}, function (response) {
          // 短信验证码发送成功
          success && success(response)
        }, function (response) {
          // 短信验证码发送失败
          failure && failure(response)
        })
      }

      // 倒计时
      function countdown(content, time) {
        if (!that.canClick) return
        that.canClick = false
        that.codeContent = that.totalTime + 's后重新发送'
          that.clock = window.setInterval(() => {
          that.totalTime--
          that.codeContent = that.totalTime + 's后重新发送'
          that.$refs.getcode.style.cssText = 'pointer-events:none;cursor: not-allowed; opacity: .6;'
          if (that.totalTime < 1) {
            window.clearInterval(that.clock)
            that.codeContent = '点击获取验证码'
            that.totalTime = 60
            that.canClick = true
            that.$refs.getcode.style.cssText = 'pointer-events:initial;cursor:initial;opacity: 1;'
          }
        }, 1000)
      }

      // 执行获取验证码逻辑
      if (that.isMobile(this.selectedMobile)) {
        that.$refs.getcode.style.cssText = 'pointer-events:none'
        requestVerifyCode(that.selectedMobile, function (data) {
          // success
          that.$set(that.$data, 'token', data.token)
          debugger
          countdown('s后重试', 60)
        }, function (data) {
          // error
          debugger
          that.showMsgModal(data.message)
          that.$refs.getcode.style.cssText = 'pointer-events:initial'
        })
      } else {
        that.$root.$emit('bv::show::tooltip', 'userMobile')
        setTimeout(function () {
          that.$root.$emit('bv::hide::tooltip')
        }, 1500)
      }
    },

    // 获取分区
    requestDistricts() {
      // 获取管理分区
      const that = this
      http.get(constant.agentDistricts, null, function (response) {
        let districtsData = response.district
        that.$set(that.$data, 'districts', districtsData)

      }, function (response) {
        console.log(response)
      })
    },

    // agent 注册提交
    bindAgentSubmit() {
      // 提交前校验
      let that = this
      let name = that.personalForm.agentName
      let mobile = that.personalForm.agentMobile
      let districtId = that.personalForm.districtId
      let email = that.personalForm.agentEmail
      let type = that.phase
      let companyName = that.personalForm.companyName

      if (!name) {
        return
      }

      if (!that.isMobile(mobile)) {
        return
      }

      if (!districtId) {
        return
      }

      if (!that.isEmial(email)) {
        return
      }

      if (!type) {
        return
      }

      if (type === 'company' && !companyName) {
        return
      }

      let postData = {
        'name': name,
        'mobile': mobile,
        'districtId': districtId,
        'email': email,
        'type': type.toUpperCase()
      }

      if (type === 'company') {
        postData = {
          'name': name,
          'mobile': mobile,
          'districtId': districtId,
          'email': email,
          'type': type.toUpperCase(),
          'companyName': companyName
        }
      }

      http.post(constant.agentApply, postData, function (response) {
        // store.dispatch('setUserName', name)
        if (type === 'company') {
          that.showAgentApply = true
        } else {
          that.showPersonalApply = true
        }
      }, function (response) {
        that.showMsgModal(response.message)
      })
    }
  },

  computed: {
    urlEncodeSelectedMobile: function () {
      return encodeURIComponent(this.selectedMobile)
    }
  },

  watch: {
    setPassword: function (val) {
      if (val) {
        this.hasPassword = true
      }
    }
  }

}
